<template>
    <div id="create-edit-container">
        <!-- use the modal component, pass in the prop -->
        <Modal v-model="stateManager.editDialogVisible"
               :title="modalTitle"
               width="60%"
               @on-cancel="closeDialog"
               :styles="{top: '20px'}"
               :mask-closable="false">

            <i-form ref="model" :model="model" :rules="ruleValidate" >
                <h4>个人信息</h4>
                <Row type="flex">
                    <i-col span="11">
                        <Form-item label="姓名" prop="name">
                            <i-input v-model="model.name" placeholder="请输入姓名"></i-input>
                        </Form-item>
                    </i-col>
                    <i-col span="11" offset="2">
                        <Form-item label="电话" prop="mobile">
                            <i-input v-model="model.mobile" placeholder="请输入电话"></i-input>
                        </Form-item>
                    </i-col>
                </Row>
                <Row type="flex">
                    <i-col span="11">
                        <Form-item label="证件类型" prop="certificates_type">
                            <Radio-group v-model="model.certificates_type" style="width: 100%">
                                <Radio :label="1">身份证</Radio>
                                <Radio :label="2">护照</Radio>
                                <Radio :label="3">通行证</Radio>
                            </Radio-group>
                        </Form-item>
                    </i-col>
                    <i-col span="11" offset="2">
                        <Form-item label="证件号码" prop="id_card">
                            <i-input v-model="model.id_card" placeholder="请输入证件号码"></i-input>
                        </Form-item>
                    </i-col>
                </Row>
                <Row type="flex" v-if="model.certificates_type != '1'">
                    <i-col span="11">
                        <Form-item label="性别" >
                            <Radio-group v-model="model.gender" style="width: 100%">
                                <Radio label="男">男</Radio>
                                <Radio label="女">女</Radio>
                            </Radio-group>
                        </Form-item>
                    </i-col>
                    <i-col span="11" offset="2">
                        <Form-item label="出身年月" >
                            <Date-picker type="date" :editable="false" @on-change="changeDob"
                                         placeholder="选择日期" v-model="model.dob" style="width: 100%"></Date-picker>
                        </Form-item>
                    </i-col>
                </Row>
                <Row type="flex">
                    <i-col span="11">
                        <Form-item label="QQ">
                            <i-input v-model="model.qq" placeholder="请输入QQ"></i-input>
                        </Form-item>
                    </i-col>
                    <i-col span="11" offset="2">
                        <Form-item label="Email">
                            <i-input v-model="model.email" placeholder="请输入Email"></i-input>
                        </Form-item>
                    </i-col>
                </Row>
                <Row type="flex">
                    <i-col span="11">
                        <Form-item label="支付宝">
                            <i-input v-model="model.alipay" placeholder="请输入支付宝账号"></i-input>
                        </Form-item>
                    </i-col>
                    <i-col span="11" offset="2">
                        <Form-item label="邮寄地址">
                            <i-input v-model="model.ems" placeholder="请输入邮寄地址"></i-input>
                        </Form-item>
                    </i-col>
                </Row>
                <h4>工作信息</h4>
                <Row type="flex">
                    <i-col span="11">
                        <Form-item label="工作省份" prop="province_id">
                            <i-select v-model="model.province_id" style="width: 100%"
                                      :filterable="true"
                                      :clearable="true"
                                      @on-change="getCityList"
                                      placeholder="请选择省份">
                                <i-option v-for="item in provinceList" :value="item.id"
                                          :key="item.id">{{item.name}}</i-option>
                            </i-select>
                        </Form-item>
                    </i-col>
                    <i-col span="11" offset="2">
                        <Form-item label="工作城市" prop="city_id">
                            <i-select v-model="model.city_id" style="width: 100%"
                                      :filterable="true"
                                      :clearable="true"
                                      placeholder="请选择城市">
                                <i-option v-for="item in cityList" :value="item.id"
                                          :key="item.id">{{item.name}}</i-option>
                            </i-select>
                        </Form-item>
                    </i-col>
                </Row>
                <Row type="flex">
                    <i-col span="11">
                        <Form-item label="工作单位" prop="work_company">
                            <i-input v-model="model.work_company" placeholder="请输入工作单位"></i-input>
                        </Form-item>
                    </i-col>
                    <i-col span="11" offset="2">
                        <Form-item label="职务">
                            <i-input v-model="model.duties" placeholder="请输入职务"></i-input>
                        </Form-item>
                    </i-col>
                </Row>
                <h4>毕业院校信息</h4>
                <Row type="flex">
                    <i-col span="11">
                        <Form-item label="省份">
                            <i-select v-model="model.finish_province_id" style="width: 100%"
                                      :filterable="true"
                                      :clearable="true"
                                      @on-change="getFinishCityList"
                                      placeholder="请选择省份">
                                <i-option v-for="item in provinceList" :value="item.id"
                                          :key="item.id">{{item.name}}</i-option>
                            </i-select>
                        </Form-item>
                    </i-col>
                    <i-col span="11" offset="2">
                        <Form-item label="城市">
                            <i-select v-model="model.finish_city_id" style="width: 100%"
                                      :filterable="true"
                                      :clearable="true"
                                      @on-change="getFinishSchoolList"
                                      placeholder="请选择城市">
                                <i-option v-for="item in finishCityList" :value="item.id"
                                          :key="item.id">{{item.name}}</i-option>
                            </i-select>
                        </Form-item>
                    </i-col>
                </Row>
                <Row type="flex">
                    <i-col span="11">
                        <Form-item label="学校">
                            <i-select v-model="model.finish_school_id" style="width: 100%"
                                      :filterable="true"
                                      :clearable="true"
                                      @on-change="getFinishDeptList"
                                      placeholder="请选择学校">
                                <i-option v-for="item in finishSchoolList" :value="item.id"
                                          :key="item.id">{{item.name}}</i-option>
                            </i-select>
                        </Form-item>
                    </i-col>
                    <i-col span="11" offset="2">
                        <Form-item label="学院">
                            <i-select v-model="model.finish_dept_id" style="width: 100%"
                                      :filterable="true"
                                      :clearable="true"
                                      @on-change="getFinishSpecialityList"
                                      placeholder="请选择学院">
                                <i-option v-for="item in finishDeptList" :value="item.id"
                                          :key="item.id">{{item.name}}</i-option>
                            </i-select>
                        </Form-item>
                    </i-col>
                </Row>
                <Row type="flex">
                    <i-col span="11">
                        <Form-item label="专业">
                            <i-select v-model="model.finish_speciality_id" style="width: 100%"
                                      :filterable="true"
                                      :clearable="true"
                                      placeholder="请选择专业">
                                <i-option v-for="item in finishSpecialityList" :value="item.id"
                                          :key="item.id">{{item.name}}</i-option>
                            </i-select>
                        </Form-item>
                    </i-col>
                    <i-col span="11" offset="2">
                        <Form-item label="入学年份" >
                            <Date-picker type="year" :editable="false" @on-change="changeSchoolYear"
                                         placeholder="选择年份" v-model="model.school_year" style="width: 100%"></Date-picker>
                        </Form-item>
                    </i-col>
                </Row>


            </i-form>

            <template slot="footer">
                <Row type="flex">
                    <i-col span="24">
                        <div class="pull-right">
                            <i-button type="ghost" @click="closeDialog">取消</i-button>
                            <i-button type="primary" @click="saveModel" :loading="isLoading">确定</i-button>
                        </div>
                    </i-col>
                </Row>
            </template>

        </Modal>

    </div>


</template>

<script>
    export default {
        props: {
            stateManager: {
                type: Object
            }
        },
        data: function () {
            const validateMobile = (rule, value, callback) => {
                let regex = /^1(3|4|5|7|8)[0-9]{9}$/;
                if (regex.test(value)){
                    callback();
                }else{
                    callback(new Error('请输入有效的电话号码！'));
                }
            };
            const validateIdCard = (rule, value, callback) => {
                if (this.model.certificates_type === 1){
                    let regex = /^(([0-9]{18})|([0-9]{17}x)|([0-9]{17}X))$/;
                    if (regex.test(value)){
                        callback();
                    }else{
                        callback(new Error('请输入有效的证件号码！'));
                    }
                }else if (this.model.certificates_type === 3){
                    let regex = /^((H[0-9]{11})|(M[0-9]{11}))$/;
                    if (regex.test(value)){
                        callback();
                    }else{
                        callback(new Error('请输入有效的证件号码！'));
                    }
                }else{
                    if (value === ''){
                        callback(new Error('请输入有效的证件号码！'));
                    }else{
                        callback();
                    }
                }
            };
            return {
                model: this.$modelDataSource({
                    url: 'api/company',
                    dataKey: 'model',
                    attributes: {
                        id: 0,
                        name: '',
                        mobile: '',
                        certificates_type: '1',
                        id_card: '',
                        gender: '',
                        dob: '',
                        qq: '',
                        email: '',
                        province_id: '',
                        city_id: '',
                        finish_province_id: '',
                        finish_city_id: '',
                        finish_school_id: '',
                        finish_dept_id: '',
                        finish_speciality_id: '',
                        work_company: '',
                        duties: '',
                        alipay: '',
                        ems: '',
                        school_year: ''
                    }
                }),
                isLoading: false,
                ruleValidate: {
                    province_id: [
                        { required: true, type: 'number', message: '请选择省份', trigger: 'change' }
                    ],
                    city_id: [
                        { required: true, type: 'number', message: '请选择城市', trigger: 'change' }
                    ],
                    certificates_type: [
                        { required: true, type: 'number', message: '请选择证件类型', trigger: 'change' }
                    ],
                    name: [
                        { required: true, message: '姓名不能为空', trigger: 'blur' }
                    ],
                    work_company: [
                        { required: true, message: '工作单位不能为空', trigger: 'blur' }
                    ],
                    mobile: [
                        { required: true, validator: validateMobile, trigger: 'blur' }
                    ],
                    id_card: [
                        { required: true, validator: validateIdCard, trigger: 'blur' }
                    ]
                },
                cityList: [],
                specialityList: [],
                finishCityList: [],
                finishSchoolList: [],
                finishDeptList: [],
                finishSpecialityList: []
            };
        },
        created: function () {
            if (this.provinceListLength < 1){
                this.$store.dispatch('fetchProvinceList');
            }
        },
        methods: {
            getCityList: function (provinceId) {
                let self = this;
                if (provinceId > 0){
                    axios.get('api/data/city-list/' + provinceId).then(function (response) {
                        self.cityList = response.data;
                    });
                }else{
                    self.cityList = [];
                    self.model.city_id = '';
                }
            },
            getFinishCityList: function (provinceId) {
                let self = this;
                if (provinceId > 0){
                    axios.get('api/data/city-list/' + provinceId).then(function (response) {
                        self.finishCityList = response.data;
                    });
                }else{
                    self.finishCityList = self.finishSchoolList = self.finishDeptList = self.finishSpecialityList = [];
                    self.model.finish_city_id = self.model.finish_school_id = self.model.finish_dept_id = self.model.finish_speciality_id = '';
                }
            },
            getFinishSchoolList: function (cityId) {
                let self = this;
                if (cityId > 0){
                    axios.get('api/data/school-list/' + cityId).then(function (response) {
                        self.finishSchoolList = response.data;
                    });
                }else{
                    self.finishSchoolList = self.finishDeptList = self.finishSpecialityList = [];
                    self.model.finish_school_id = self.model.finish_dept_id = self.model.finish_speciality_id = '';
                }
            },
            getFinishDeptList: function (schoolId) {
                let self = this;
                if (schoolId > 0){
                    axios.get('api/data/dept-list/' + schoolId).then(function (response) {
                        self.finishDeptList = response.data;
                    });
                }else{
                    self.finishDeptList = self.finishSpecialityList = [];
                    self.model.finish_dept_id = self.model.finish_speciality_id = '';
                }
            },
            getFinishSpecialityList: function (deptId) {
                let self = this;
                if (deptId > 0){
                    axios.get('api/data/speciality-list/' + deptId).then(function (response) {
                        self.finishSpecialityList = response.data;
                    });
                }else{
                    self.finishSpecialityList = [];
                    self.model.finish_speciality_id = '';
                }
            },
            changeDob: function (newTime) {
                if (this.model.dob !== newTime){
                    this.model.dob = newTime;
                }else{
                    this.model.dob = '';
                }
            },
            changeSchoolYear: function (newTime) {
                if (this.model.school_year !== newTime){
                    this.model.school_year = newTime;
                }else{
                    this.model.school_year = '';
                }
            },
            closeDialog: function () {
                this.stateManager.editDialogVisible = false;
                this.model.reset();
                this.$refs['model'].resetFields();
                this.stateManager.editModelId = 0;
            },
            saveModel: function () {
                let self = this;
                self.$refs['model'].validate((valid) => {
                    if (valid){
                        console.log('表单验证通过');
                        self.isLoading = true;
                        self.model.save(function () {
                            self.$Notice.success({
                                title: '保存成功',
                                desc: self.model.name
                            });
                            self.isLoading = false;
                            self.closeDialog();
                            self.stateManager.refreshList = true;
                        }, function () {
                            console.log(self.model.errors);
                            self.isLoading = false;
                            _.forOwn(self.model.errors, function (value, key) {
                                if (value){
                                    self.$Notice.error({
                                        title: '保存失败',
                                        desc: value
                                    });
                                }
                            });
                        });
                    }else{
                        console.log('表单验证失败');
                    }
                });
            }
        },
        computed: {
            modalTitle: function () {
                if (this.model.id === 0){
                    return '添加社会用户';
                }else{
                    return '修改社会用户';
                }
            },
            provinceList(){
                return this.$store.state.provinceList;
            },
            provinceListLength(){
                return this.$store.getters.getProvinceListLength;
            }
        },
        watch: {
            'stateManager.editModelId': function (newValue) {
                let self = this;
                this.model.fetch(newValue, function () {
                    self.stateManager.buttonLoading = false;
                    self.stateManager.editDialogVisible = true;
                }, function () {
                    self.stateManager.buttonLoading = false;
                    self.$Notice.error({
                        title: '数据加载超时',
                        desc: '请尝试刷新页面，并仔细检查网络链接状况或联系技术人员！'
                    });
                });
            }
        }
    }
</script>

<style>

</style>